package com.dwsoft.word;

import com.dwsoft.utils.XStreamUtil;
import com.dwsoft.xml.XDocument;
import com.dwsoft.xml.XmlNode;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import word.w2004.Document2004;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author sqw
 * @version 1.0
 * @description TODO
 * @ClassName ParagraphContext
 * @Date 2020/8/5
 * @since jdk1.8
 */
@Component
public class ElementContext implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ElementContext.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }


    public WElement getBean(String name){
        WElement strategy = (WElement) applicationContext.getBean(name);
        return strategy;
    }

    //通过name获取 Bean.
    public Document2004 xmlToWord(String xml,Map<String,String> params) throws Exception {
        Document2004 document = new Document2004();
        XDocument documentNode = (XDocument) XStreamUtil.xmlToBean(xml);
        //标题栏
        WElement titleElement = (WElement) applicationContext.getBean("title");
        titleElement.instance(documentNode,document);
        List<XmlNode> xmlNodes = documentNode.getXmlNodes();
        for(int i=0;i<xmlNodes.size();i++){
            XmlNode xmlNode = xmlNodes.get(i);
            xmlNode.setIndex((i+1)+"");
            String className=xmlNode.getClass().getSimpleName().substring(1).toLowerCase();
            WElement strategy = (WElement) applicationContext.getBean(className);
            strategy.setParams(params);
            strategy.instance(xmlNode,document);
        }
        return document;
    }

}
